<template>
    <div class="client">
        <el-form
            ref="formRef"
            :model="formData"
            :rules="rules"
            label-width="100px"
            :size="'default'"
            status-icon
        >
            <el-row :gutter="2">
                <el-col :span="12">
                    <el-form-item label="中文名称" prop="client_nam_c">
                        <el-input v-model.trim="formData.client_nam_c" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="英文名称" prop="client_nam_e">
                        <el-input v-model.trim="formData.client_nam_e" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="中文简称" prop="client_short_c">
                        <el-input v-model.trim="formData.client_short_c" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="英文简称" prop="client_short_e">
                        <el-input v-model.trim="formData.client_short_e" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model.trim="formData.email" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="运输公司" prop="trans_corp_id">
                        <el-switch v-model="formData.trans_corp_id" :active-value="'Y'"
                            :inactive-value="'N'"></el-switch>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="供应商" prop="provid_id">
                        <el-switch v-model="formData.provid_id" :active-value="'Y'"
                            :inactive-value="'N'"></el-switch>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="成本中心" prop="cntr_owner_id">
                        <el-switch v-model="formData.cntr_owner_id" :active-value="'Y'"
                            :inactive-value="'N'"></el-switch>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="修箱公司" prop="repair_id">
                        <el-switch v-model="formData.repair_id" :active-value="'Y'"
                            :inactive-value="'N'"></el-switch>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="场站" prop="cfs_id">
                        <el-switch v-model="formData.cfs_id" :active-value="'Y'"
                            :inactive-value="'N'"></el-switch>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="客户" prop="custom_id">
                        <el-switch v-model="formData.custom_id" :active-value="'Y'"
                            :inactive-value="'N'"></el-switch>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col>
                    <el-form-item label="备注" prop="remark">
                        <el-input v-model="formData.remark" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>
    <div class="bank">
        <el-table
            ref="tableRef"
            :data="tableData"
            row-key="id"
            table-layout="auto"
            @row-dblclick="onBankClick"
            @cell-click="onDefaultIdClick"
        >
            <template #empty>
                <span>无数据</span>
            </template>
            <el-table-column
                v-bind:align="'center'"
                prop="default_id"
                label="默认"
                width="80"
            >
                <template #default="scope">
                        <el-switch
                            v-model="scope.row.default_id"
                            :active-value="'Y'"
                            :inactive-value="'N'"
                        ></el-switch>
                </template>
            </el-table-column>
            <el-table-column
                v-bind:align="'center'"
                prop="bank_nam"
                label="银行名称"
                width="280"
            >
                <template #default="scope">
                    <template v-if="scope.row.isEdit">
                        <el-input v-model="scope.row.bank_nam"></el-input>
                    </template>
                    <template v-else>
                        {{ scope.row.bank_nam }}
                    </template>
                </template>
            </el-table-column>
            <el-table-column
                v-bind:align="'center'"
                prop="bank_account"
                label="银行账号"
                width="280"
            >
                <template #default="scope">
                    <template v-if="scope.row.isEdit">
                        <el-input v-model="scope.row.bank_account"></el-input>
                    </template>
                    <template v-else>
                        {{ scope.row.bank_account }}
                    </template>
                </template>
            </el-table-column>
            <el-table-column
                v-bind:align="'center'"
                prop="remark"
                label="备注"
                width="280"
            >
                <template #default="scope">
                    <template v-if="scope.row.isEdit">
                        <el-input v-model="scope.row.remark"></el-input>
                    </template>
                    <template v-else>
                        {{ scope.row.remark }}
                    </template>
                </template>
            </el-table-column>
            <el-table-column>
                <template #default="scope">
                    <template v-if="scope.row.isEdit">
                        <el-button
                            size="small"
                            type="primary"
                            @click="onOK(scope.$index, scope.row)"
                            >确定</el-button
                        >
                        <el-button
                            size="small"
                            type="info"
                            @click="onCancel(scope.$index, scope.row)"
                            >取消</el-button
                        >
                        <el-button
                            size="small"
                            type="warning"
                            @click="onDel(scope.$index, scope.row)"
                            >删除</el-button
                        >
                    </template>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <div class="btn-group">
        <el-button-group>
            <el-button
                class="btn"
                type="primary"
                v-debounce="submitForm"
                size="large"
            >
                保存
            </el-button>
            <el-button
                class="btn"
                type="primary"
                v-debounce="submitAndNewForm"
                size="large"
            >
                保存并新增
            </el-button>
            <el-button class="btn" type="primary" @click="addBank" size="large" disabled
                >增加账号</el-button
            >
        </el-button-group>
    </div>
</template>
<script setup lang="ts" name="Client">
import { ref, reactive, onMounted, toValue } from 'vue';
import {
    ElMessage,
    type FormInstance,
    type FormRules,
    type TableRefs,
} from 'element-plus';

import type {
    ClientBankModel,
    ClientModel,
} from '@/common/types/basedataModel';
import { Request } from '@/app/request';

import { initObjectProperty } from '@/common/tools';
import { omit, template } from 'lodash';
import { ValidateFieldsError } from 'async-validator';


const props = defineProps<{
    client: ClientModel;
}>();
const temBank: ClientBankModel = {};
const formRef = ref<FormInstance>();
const formData = reactive<ClientModel>({});
const tableRef = ref<TableRefs>();
const tableData = reactive<ClientBankModel[]>([]);
const rules = reactive<FormRules>({
    client_nam_c: [
        { required: true, message: '请输入客户中文名称', trigger: 'blur' },
        { max: 60, message: '中文长度不能超过60位', trigger: 'blur' },
    ],
    email: [
        {type: 'email', message: '邮箱格式错误', trigger: 'blur'}
    ]
});

const emit = defineEmits<{
    create: [action: ClientModel];
    update: [action: ClientModel];
    close: [];
}>();
onMounted(() => {
    Object.assign(formData, omit(props.client, ['banks']));
    if (props.client.banks) {
        props.client.banks!.forEach((element: ClientBankModel) => {
            tableData.push(element);
        });
    }
});
const save = async () => {
    const formValid = await formRef.value?.validate(
        (isValid: boolean, _invalidFields?: ValidateFieldsError) => {
            // return isValid;
        },
    );
    if (formValid) {
        for (let index = 0; index < tableData.length; index++) {
            const element = tableData[index];
            if (!element.bank_nam) {
                ElMessage({
                    type: 'info',
                    dangerouslyUseHTMLString: true,
                    message: '银行名称不能为空',
                });
                return;
            }
            if (!element.bank_account) {
                ElMessage({
                    type: 'info',
                    dangerouslyUseHTMLString: true,
                    message: '银行账号不能为空',
                });
                return;
            }
            if (element.isEdit) {
                ElMessage({
                    type: 'info',
                    dangerouslyUseHTMLString: true,
                    message: '存在未确定数据',
                });
                return;
            }
        }
        if (formData.id! > 0) {
            // 修改
            formData['banks'] = tableData;
            const req = new Request('客户修改', formData);
            const r = await req.post();
            if (r.code > 100) {
                emit('update', formData);
                return true;
            }
        } else {
            // 新增
            const param = omit(formData, ['id']);
            param['banks'] = tableData;
            const req = new Request('客户增加', param);
            const r = await req.post();
            if (r.code > 100) {
                emit('create', r.obj as ClientModel);
                return true;
            }
        }
        /* const param = omit(formData, ['id']);
        param['feedet'] = toValue(tableData);
        const req = new Request('箱进场', param);
        const r = await req.post();
        if (r.code > 100) {
            // emit('create', r.obj as CntrModel);

            return true;
        } */
    } else {
        return false;
    }
};
const submitForm = async () => {
    const r = await save();
    if (r) {
        emit('close');
    }
};

const submitAndNewForm = async () => {
    const r = await save();
    if (r) {
        reset();
    }
};
const reset = () => {
    initObjectProperty(formData);
    initObjectProperty(temBank);
    tableData.length = 0;
};
const addBank = () => {
    tableData.push({
        isEdit: true,
    });
    initObjectProperty(temBank);
};
const onOK = (_index: number, row: ClientBankModel) => {
    row.isEdit = false;
    initObjectProperty(temBank);
};
const onCancel = (_index: number, row: ClientBankModel) => {
    Object.assign(row, temBank);
    row.isEdit = false;
};
const onDel = (index: number, row: ClientBankModel) => {
    tableData.splice(index, 1);
};
const onBankClick = (row: any, column: any, event: Event) => {
    // console.log(row);
    Object.assign(temBank, omit(row, ['isEdit']));
    row.isEdit = true;
};
const onDefaultIdClick = (row: any, column: any, cell: HTMLTableCellElement, event: Event) => {
    if (column.label === '默认') {
        if (row.default_id === 'Y') {
            tableData.forEach((element: ClientBankModel) => {
                if (element.default_id === 'Y' && row != element) {
                    element.default_id = 'N';
                }
            });
        }
    }
}
</script>
<style lang="scss" scoped>
.client {
    margin-bottom: 20px;
    padding: 10px 10px;
    border: solid 2px var(--el-color-primary);
    box-shadow: 10px 10px 5px rgba(100, 100, 100, 0.5);
}
.bank {
    margin-bottom: 20px;
    padding-top: 10px 10px;
    border: solid 2px var(--el-color-primary);
    box-shadow: 10px 10px 5px rgba(100, 100, 100, 0.5);
}
.btn-group {
    .btn {
        margin-right: 5px;
    }
}
</style>
